package com.my.demo.controller.personal;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.demo.pojo.FamilyInformation;
import com.my.demo.pojo.Person;
import com.my.demo.pojo.Result;
import com.my.demo.service.FamilyInformationService;
import com.my.demo.service.IdentifyService;
import com.my.demo.service.PerIdentifyService;
import com.my.demo.service.PersonService;
import com.my.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
public class SearchPersonController {
  @Autowired
  FamilyInformationService familyInformationService;
  @Autowired
  PersonService personService;
  @Autowired
  IdentifyService identifyService;
  @Autowired
  PerIdentifyService perIdentifyService;
  @Autowired
  UserService userService;

  /*
   * 搜索家谱：根据输入的人名进行搜索，朝代暂时不考虑，看是否需要在家谱中增添一个字段，来表示人物所在的朝代
   * 搜索出来的家谱应该还要增加一个修改功能，对于每一个人的信息，输入他的名字，应该要能够进行对应地修改
   * 输入人物名称，在当前登录用户的所有家谱中去寻找，看这个人是不是存在在这些家谱中
   * 输入居住地，应该是根据所在家谱表中的居住地，这个应该是企业用户的功能，个人用户应该只能看到他自己的家谱，居住地应该只有一个
   * 输入家谱名，这个可以直接找到对应的家谱
   * 以上所有的搜索条件应该是and连接
   * 以上所有的搜索条件应该允许某个条件为空
   * 有可能用户什么都不输入，我们最终找不到对应的家谱，这个应该要予以提示，以及后端应该要避免出错
   *
   * 得到的结果应该是家谱的编号，最好是家谱的编号，然后再在里面找，
   *
   * 如果搜索里面人物名为空，那么只需要返回对应的家谱里面的信息
   * 如果搜索里面人物名不为空，那么需要返回查找到的人的信息，因此这里应该是有两个不同的搜索结果界面：
   * 1.一个给出了人物名以及其个人信息
   * 2.一个没有给出人物名，仅仅是给出了家谱的信息
   * 而且还必须给出一个按钮，查看搜索到的家谱
   *
   * 前端推进到另一个界面，请求后端发送数据
   */


  @PostMapping("search_person_personal")
  @CrossOrigin
  public Result searchPersonPersonal(@RequestBody Map<String,String> map){
    Result result = new Result();
    result.setMsg(null);
    result.setSuccess(false);
    System.out.println("开始请求:"+map);

    String name = null;
    try {
      name = map.get("name");
    }catch (Exception exception){
      exception.printStackTrace();
    }
    QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
    if (name!=null && !name.equals("")){
      personQueryWrapper.like("name",name);
      System.out.println("家谱名："+name);
    }

    String habitation = null;
    try {
      habitation = map.get("habitation");
    }catch (Exception exception){
      exception.printStackTrace();
    }
    QueryWrapper<FamilyInformation> familyInformationQueryWrapper = new QueryWrapper<>();
    if (habitation!=null && !habitation.equals("")){
      familyInformationQueryWrapper.like("residence",habitation);
      System.out.println("居住地："+habitation);
    }
    String household = null;
    try {
      household = map.get("household");
    }catch (Exception exception){
      exception.printStackTrace();
    }
    if (household!=null && !household.equals("")){
      familyInformationQueryWrapper.like("household",household);
      System.out.println("堂号："+household);
    }

    String genealogyName = null;
    try {
      genealogyName = map.get("genealogyName");
    }catch (Exception exception){
      exception.printStackTrace();
    }
    if (genealogyName!=null && !genealogyName.equals("")){
      familyInformationQueryWrapper.like("name",genealogyName);
      System.out.println("家谱名："+genealogyName);
    }

    //获取当前用户的ID,如果userId>0说明获取到了正确的userId
    Integer userId=0;
    try {
      String userName = (String) SecurityUtils.getSubject().getPrincipal();
      userId = userService.selectIdByName(userName);
    }catch (Exception exception){
      exception.printStackTrace();
    }
    if (userId!=null&&userId>0){
      familyInformationQueryWrapper.eq("uploader",userId);
    }
    else {
      //没有获取到当前用户的ID,说明出现了问题
      return result;
    }

    /*
     * 接下来开始搜索家谱，并且获取到其所有符合条件的家谱ID
     * */
    List<FamilyInformation> familyInformationList = null;
    try{
      familyInformationList=familyInformationService.list(familyInformationQueryWrapper);
    }catch (Exception exception){
      exception.printStackTrace();
    }
    if (familyInformationList==null || familyInformationList.isEmpty()){
      //没有合适的家谱
      return result;
    }
    else {
      List<Integer> familyIDList=new ArrayList<>();
      for (FamilyInformation familyInformation : familyInformationList) {
        System.out.println("家谱为："+familyInformation);
        familyIDList.add(familyInformation.getFamilyArchiveId());
      }
      personQueryWrapper.in("family_archive_id",familyIDList);
      List<Person> personList = null;
      try {
        personList = personService.list(personQueryWrapper);
      }catch (Exception exception){
        exception.printStackTrace();
      }
      if (personList==null || personList.isEmpty() ){
        return result;
      }
      List<Map> resultList = new ArrayList<>();
      for (Person person : personList) {
        Map<String,Object> mapMed = new HashMap<>();
        mapMed.put("lastName",person.getLastName());
        mapMed.put("firstName",person.getFirstName());
        mapMed.put("mother",person.getMother());
        mapMed.put("childType",person.getChildType());
        mapMed.put("mainIntroduction",person.getMainIntroduction());
        mapMed.put("seniority",person.getSeniority());
        mapMed.put("ranking",person.getRanking());
        mapMed.put("genealogyId",person.getFamilyArchiveId());

        //找到该人父亲的信息
        Integer fatherId = null;
        try {
          fatherId = person.getFatherId();
        }catch (Exception exception){
          exception.printStackTrace();
        }
        if (fatherId!=null&&fatherId!=0){
          Person father = null;
          try {
            QueryWrapper<Person> fatherQuery = new QueryWrapper<>();
            fatherQuery.eq("person_id",fatherId);
            father = personService.getOne(fatherQuery);
          }catch (Exception exception){
            exception.printStackTrace();
          }
          //如果父亲存在，则将父亲的信息存入到map中
          if (father!=null){
            mapMed.put("father",father.getName());
          }
          else {
            mapMed.put("father","");
          }
        }
        else {
          mapMed.put("father","");
        }

        //找到该人所在的家谱名
        Integer familyArchiveId = null;
        try {
          familyArchiveId = person.getFamilyArchiveId();
        }catch (Exception exception){
          exception.printStackTrace();
        }
        if (familyArchiveId!=null && familyArchiveId!=0){
          QueryWrapper<FamilyInformation> familyQuery  = new QueryWrapper<>();
          familyQuery.eq("family_archive_id",familyArchiveId);
//                    System.out.println("家谱编号为："+familyArchiveId);
          FamilyInformation familyInformation = null;
          try {
            familyInformation = familyInformationService.getOne(familyQuery);
          }catch (Exception exception){
            exception.printStackTrace();
          }
//                    System.out.println("获取的家谱为："+familyInformation);
          if (familyInformation!=null){
            mapMed.put("genealogyName",familyInformation.getName());
          }
        }
        resultList.add(mapMed);
      }
      Map<String,Object> resultMap = new HashMap<>();
      resultMap.put("total",personList.size());
      resultMap.put("result",resultList);
      result.setDetail(resultMap);
      result.setMsg("搜索成功");
      result.setSuccess(true);
    }
    return result;
  }

  @PostMapping("search_person_all")
  @CrossOrigin
  public Result searchPersonAll(@RequestBody Map<String,String> map){
    Result result = new Result();
    result.setMsg(null);
    result.setSuccess(false);
    System.out.println("开始请求:"+map);

    String name = null;
    try {
      name = map.get("name");
    }catch (Exception exception){
      exception.printStackTrace();
    }
    QueryWrapper<Person> personQueryWrapper = new QueryWrapper<>();
    if (name!=null && !name.equals("")){
      personQueryWrapper.like("name",name);
      System.out.println("人物名："+name);
    }

    String habitation = null;
    try {
      habitation = map.get("habitation");
    }catch (Exception exception){
      exception.printStackTrace();
    }
    QueryWrapper<FamilyInformation> familyInformationQueryWrapper = new QueryWrapper<>();
    if (habitation!=null && !habitation.equals("")){
      familyInformationQueryWrapper.like("residence",habitation);
      System.out.println("居住地："+habitation);
    }
    String household = null;
    try {
      household = map.get("household");
    }catch (Exception exception){
      exception.printStackTrace();
    }
    if (household!=null && !household.equals("")){
      familyInformationQueryWrapper.like("household",household);
      System.out.println("堂号："+household);
    }

    String genealogyName = null;
    try {
      genealogyName = map.get("genealogyName");
    }catch (Exception exception){
      exception.printStackTrace();
    }
    if (genealogyName!=null && !genealogyName.equals("")){
      familyInformationQueryWrapper.like("name",genealogyName);
      System.out.println("家谱名："+genealogyName);
    }

    /*
     * 接下来开始搜索家谱，并且获取到其所有符合条件的家谱ID
     * */
    List<FamilyInformation> familyInformationList = null;
    try{
      familyInformationList=familyInformationService.list(familyInformationQueryWrapper);
    }catch (Exception exception){
      exception.printStackTrace();
    }
    if (familyInformationList==null || familyInformationList.isEmpty()){
      //没有合适的家谱
      return result;
    }
    else {
      List<Integer> familyIDList=new ArrayList<>();
      for (FamilyInformation familyInformation : familyInformationList) {
        familyIDList.add(familyInformation.getFamilyArchiveId());
      }
      personQueryWrapper.in("family_archive_id",familyIDList);
      List<Person> personList = null;
      try {
        personList = personService.list(personQueryWrapper);
      }catch (Exception exception){
        exception.printStackTrace();
      }
      if (personList==null || personList.isEmpty() ){
        return result;
      }
      List<Map> resultList = new ArrayList<>();
      for (Person person : personList) {
        Map<String,Object> mapMed = new HashMap<>();
        mapMed.put("lastName",person.getLastName());
        mapMed.put("firstName",person.getFirstName());
        mapMed.put("mother",person.getMother());
        mapMed.put("childType",person.getChildType());
        mapMed.put("mainIntroduction",person.getMainIntroduction());
        mapMed.put("seniority",person.getSeniority());
        mapMed.put("ranking",person.getRanking());
        mapMed.put("genealogyId",person.getFamilyArchiveId());

        //找到该人父亲的信息
        Integer fatherId = null;
        try {
          fatherId = person.getFatherId();
        }catch (Exception exception){
          exception.printStackTrace();
        }
        if (fatherId!=null&&fatherId!=0){
          Person father = null;
          try {
            QueryWrapper<Person> fatherQuery = new QueryWrapper<>();
            fatherQuery.eq("person_id",fatherId);
            father = personService.getOne(fatherQuery);
          }catch (Exception exception){
            exception.printStackTrace();
          }
          //如果父亲存在，则将父亲的信息存入到map中
          if (father!=null){
            mapMed.put("father",father.getName());
          }
          else {
            mapMed.put("father","");
          }
        }
        else {
          mapMed.put("father","");
        }

        //找到该人所在的家谱名
        Integer familyArchiveId = null;
        try {
          familyArchiveId = person.getFamilyArchiveId();
        }catch (Exception exception){
          exception.printStackTrace();
        }
        if (familyArchiveId!=null && familyArchiveId!=0){
          QueryWrapper<FamilyInformation> familyQuery  = new QueryWrapper<>();
          familyQuery.eq("family_archive_id",familyArchiveId);
//                    System.out.println("家谱编号为："+familyArchiveId);
          FamilyInformation familyInformation = null;
          try {
            familyInformation = familyInformationService.getOne(familyQuery);
          }catch (Exception exception){
            exception.printStackTrace();
          }
//                    System.out.println("获取的家谱为："+familyInformation);
          if (familyInformation!=null){
            mapMed.put("genealogyName",familyInformation.getName());
          }
        }
        resultList.add(mapMed);
      }
      Map<String,Object> resultMap = new HashMap<>();
      resultMap.put("total",personList.size());
      resultMap.put("result",resultList);
      result.setDetail(resultMap);
      result.setMsg("搜索成功");
      result.setSuccess(true);
    }
    return result;
  }

//    @PostMapping("get_search_result")
//    @CrossOrigin
//    public Result getSearchGenealogy(@RequestBody Map<String,Integer> map, HttpSession session){
//        Result result = new Result();
//        result.setSuccess(false);
//        result.setMsg(null);
//
//        String searchResultType = null;
//        try {
//            searchResultType = (String) session.getAttribute("searchResultType");
//        }catch (Exception exception){
//            exception.printStackTrace();
//        }
//        System.out.println("searchResultType:"+searchResultType);
//       /*
//        * 获取搜索结果，并且分页显示
//        * 参数为pageNumber
//        */
//        Integer pageNumber = map.get("pageNumber");
//        if (pageNumber==null){
//            pageNumber=1;
//        }
//        //搜索结果为空
//        if (searchResultType==null){
//            result.setMsg("没有符合查询条件的数据");
//            return result;
//        }
//        //搜索结果类型为人物
//        else if (searchResultType == "person"){
//            List<Integer> personIdList = null;
//            try {
//                personIdList = (List<Integer>) session.getAttribute("searchResult");
//            }catch (Exception exception){
//                exception.printStackTrace();
//            }
//            if (personIdList == null){
//                return result;
//            }
//            QueryWrapper<Person> personQueryWrapper = new QueryWrapper<Person>();
//            personQueryWrapper.in("person_id",personIdList);
//            try {
//                Page<Person> personPage = new Page<>(pageNumber,5);//每页五条记录
//                Page<Person> page = personService.page(personPage,personQueryWrapper);
//                result.setDetail(page);
//                result.setSuccess(true);
//                result.setMsg("获取数据成功");
//            }catch (Exception exception){
//                exception.printStackTrace();
//            }
//        }
//        else {
//            List<Integer> familyIdList =null;
//            try {
//                familyIdList =(List<Integer>) session.getAttribute("searchResult");
//            }catch (Exception exception){
//                exception.printStackTrace();
//            }
//            if (familyIdList == null){
//                return result;
//            }
//            QueryWrapper<FamilyInformation> familyInformationQueryWrapper = new QueryWrapper<FamilyInformation>();
//            familyInformationQueryWrapper.in("family_archive_id",familyIdList);
//            try {
//                Page<FamilyInformation> familyInformationPage = new Page<>(pageNumber,5);
//                Page<FamilyInformation> page = familyInformationService.page(familyInformationPage,familyInformationQueryWrapper);
//                result.setMsg("获取数据成功");
//                result.setSuccess(true);
//                result.setDetail(page);
//            }catch (Exception exception){
//                exception.printStackTrace();
//            }
//        }
//        return result;
//    }
}

